﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Taurus.Platform.BLL;
using Taurus.Master.DTO;

namespace Taurus.Master.BLL
{
    class InitSys
    {
        #region field
        private static InitSys _is;

        /// <summary>
        /// MyGarage集合
        /// </summary>
        private Dictionary<string, Master> _master;
        private Dictionary<string, ManualResetEvent> _manualResetEvent;

        /// <summary>
        /// 账号逻辑
        /// </summary>
        private AccountBll _ab;
        #endregion

        #region construction

        private InitSys() {
            _ab = new AccountBll();
            _master = new Dictionary<string, Master>();
            _manualResetEvent = new Dictionary<string, ManualResetEvent>();
        }

        #endregion

        #region property

        public static InitSys Instance
        {
            get
            {
                if (_is == null)
                {
                    _is = new InitSys();
                }
                return _is;
            }
        }

        public List<Master> MasterList
        {
            get
            {
                return _master.Values.ToList();
            }
        }

        #endregion

        #region private method

        private void InitMaster(object o)
        {
            PKer p = (PKer)o;
            Master m = new Master(p);
            m.UpdateInfo();
            _master.Add(p.UID, m);
            _manualResetEvent[p.UID].Set();
        }

        #endregion

        #region public method

        public void Init()
        {
            foreach (var ua in _ab.GetAllAccount())
            {
                PKer p = new PKer(ua);
                _manualResetEvent.Add(p.UID, new ManualResetEvent(false));
                ThreadPool.QueueUserWorkItem(new WaitCallback(InitMaster), p);
            }
            WaitHandle.WaitAll(_manualResetEvent.Values.ToArray());
        }

        public Master GetMaster(string uid)
        {
            return _master[uid];
        }

        #endregion


    }
}
